package com.spring.mvc.http.test;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * 单向加密算法主要有：MD5(Message-digest Algorithm) SHA
 * @author Administrator
 *
 */
public class SingleDemo {

	public byte[] encrypt(String str){
		try {
			//根据MD5算法生成MessageDigest对象
			//MD5 SHA
			MessageDigest md=MessageDigest.getInstance("MD5");
			byte[] srcBytes=str.getBytes();
			md.update(srcBytes);
			//完成哈希计算，得到result
			byte[] result=md.digest();
			return result;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		String str="hello world!";
		try {
			KeyGenerator keyGen=KeyGenerator.getInstance("DESede");
			SecretKey key=keyGen.generateKey();
			byte[] keyBytes=key.getEncoded();
			
			//生成MAC对象
			SecretKeySpec SKS=new SecretKeySpec(keyBytes, "HMACMD5");
			Mac mac=Mac.getInstance("HMACMD5");
			mac.init(SKS);
			//传入要计算验证码的的字符串
			mac.update(str.getBytes("UTF-8"));
			//计算验证码
			byte[] certifyCode=mac.doFinal();
			for (int i = 0; i < certifyCode.length; i++) {
				System.out.println(certifyCode[i]);
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
}
